package com.security.handler;

import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @USER: ysx
 * @CREATE: 2021/1/26 16:28
 * 自定义登录成功后的处理器
 * 转发或者重定向，由代码逻辑实现
 */
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    private String url;
    private boolean isRedirect;
    public MyAuthenticationSuccessHandler(String url, boolean isRedirect) {
        this.url = url;
        this.isRedirect = isRedirect;
    }

    /**
     *
     * @param request   请求对象    request.getRequestDispatcher().forward()
     * @param response  响应对象    response.sendRedirect()
     * @param authentication    用户认证（登录）成功后的对象。其中包含用户名和权限集合。内容是
     *                          自定义的UserDetailsService实现的方法值对象提供的
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException, ServletException {
        System.out.println(request.getRemoteHost());
        System.out.println(request.getRemoteAddr());
        System.out.println("自定义认证处理逻辑执行");
        if (isRedirect) {
            response.sendRedirect(url);
        }else {
            request.getRequestDispatcher(url).forward(request, response);
        }

    }

    //getter和setter不是必要的
    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public boolean isRedirect() {
        return isRedirect;
    }

    public void setRedirect(boolean redirect) {
        isRedirect = redirect;
    }
}
